import { Form, Input, Select, Table } from 'myselfantd';
import { useEffect, useState } from 'react';
// import { getList } from '../api';
import _ from 'lodash';

interface FormProps {
  mapPoint?: string;
  data?: any;
  onFinish: Function;
}
const App = ({ data, onFinish }: FormProps) => {
  const initForm = [
    [
      {
        name: 'name',
        label: '属性名称',
        rules: [{ required: true, message: '属性名称必填' }],
        render: () => <Input placeholder="请输入" />,
      },
      {
        name: 'code',
        label: '标识符',
        rules: [{ required: true, message: '标识符必填' }],
        render: () => <Input placeholder="请输入" />,
      },
    ],
    [
      {
        name: 'type',
        label: '数据类型',
        rules: [{ required: true, message: '数据类型必填' }],
        render: () => (
          <Select
            placeholder="请选择"
            onChange={(value: string) => {
              setSelectType(value);
            }}
            allowClear
          >
            <Select.Option value={1} key="1">
              数字类型
            </Select.Option>
            <Select.Option value={2} key="2">
              字符串类型
            </Select.Option>
            <Select.Option value={3} key="3">
              布尔类型
            </Select.Option>
            <Select.Option value={4} key="4">
              枚举类型
            </Select.Option>
          </Select>
        ),
      },
      {
        name: 'readWriteType',
        label: '读写类型',
        rules: [{ required: true, message: '读写类型必填' }],
        render: () => (
          <Select placeholder="请选择读写类型" allowClear>
            <Select.Option value={1} key="1">
              读
            </Select.Option>
            <Select.Option value={2} key="2">
              读写
            </Select.Option>
          </Select>
        ),
      },
    ],
  ];
  const [selectType, setSelectType] = useState(data.type);
  const [formItemData, setFormItemData] = useState<any>(initForm);
  useEffect(() => {
    switch (selectType) {
      case 1:
        setFormItemData([
          ...initForm,
          [
            {
              name: 'defaultValue',
              label: '默认值',
              render: () => <Input placeholder="请输入" />,
            },
            {
              label: '定义取值范围',
              style: { marginBottom: 0 },
              render: () => (
                <Input.Group
                  compact
                  style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-around' }}
                >
                  <Form.Item name="min" rules={[{ required: true, message: '最小值必填' }]}>
                    <Input placeholder="最小值" />
                  </Form.Item>
                  <span style={{ textAlign: 'center', margin: '6px 10px' }}>-</span>
                  <Form.Item name="max" rules={[{ required: true, message: '最大值必填' }]}>
                    <Input placeholder="最大值" />
                  </Form.Item>
                </Input.Group>
              ),
            } as any,
          ],
          [
            {
              name: 'unitId',
              label: '单位',
              rules: [{ required: true, message: '单位必填' }],
              render: () => (
                <Select
                  fieldNames={{ name: 'name', value: 'id' }}
                  request={async () => {
                    // let { result } = await getList({});
                    // return result;
                    return []
                  }}
                  placeholder="请选择"
                  allowClear
                />
              ),
            },
            {
              name: 'walkLength',
              label: '步长',
              render: () => <Input placeholder="请输入" />,
            },
          ],
        ]);
        break;
      case 2:
        setFormItemData([
          ...initForm,
          [
            {
              name: 'defaultValue',
              label: '默认值',
              render: () => <Input placeholder="请输入" />,
            },
            {
              name: 'stringResult',
              label: '数据长度',
              rules: [{ required: true, message: '数据长度必填' }],
              render: () => <Input />,
            },
          ],
        ]);
        break;
      case 3:
        setFormItemData([
          ...initForm,
          [
            {
              name: 'defaultValue',
              label: '默认值',
              render: () => <Input placeholder="请输入" />,
            },
          ],
          [
            {
              name: 'booleanEnums',
              label: '布尔值',
              rules: [
                {
                  validator: (_: any, value: any) => {
                    if (value.some((item: any) => item.enumDesc === '')) {
                      return Promise.reject('布尔值必填');
                    } else {
                      return Promise.resolve();
                    }
                  },
                  trigger: 'blur',
                },
              ],
              render: (data: any) => {
                return (
                  <Table.Edit
                    deleteButton={false}
                    defaultValue={[
                      { sortkey: 1, enumKey: 'true', enumDesc: '' },
                      { sortkey: 2, enumKey: 'false', enumDesc: '' },
                    ]}
                    pagination={false}
                    columns={[
                      {
                        title: '参数值',
                        dataIndex: 'enumKey',
                        showSorterTooltip: false,
                        width: 180,
                        onCell: (record: any) => {
                          return {
                            filed: 'enumKey',
                            record,
                            rules: [
                              {
                                required: true,
                                message: `参数值必填`,
                              },
                            ],
                            // render: (inputRef:HTMLInputElement) => (
                            //   <Form.Item
                            //     style={{ margin: 0 }}
                            //     name={'name'}
                            //     rules={[
                            //       {
                            //         required: true,
                            //         message: `参数名称必填`,
                            //       },
                            //     ]}
                            //   >
                            //     <Input ref={inputRef} onPressEnter={handleSave} onBlur={handleSave} />
                            //   </Form.Item>
                            // ),
                          };
                        },
                      },
                      {
                        title: '参数描述',
                        dataIndex: 'enumDesc',
                        showSorterTooltip: false,
                        onCell: (record: any) => ({
                          editable: true,
                          filed: 'enumDesc',
                          record,
                          rules: [
                            {
                              required: true,
                              message: `参数描述必填`,
                            },
                          ],
                        }),
                      },
                    ]}
                  />
                );
              },
            },
          ],
        ]);
        break;
      case 4:
        setFormItemData([
          ...initForm,
          [
            {
              name: 'defaultValue',
              label: '默认值',
              render: () => <Input placeholder="请输入" />,
            },
          ],
          [
            {
              name: 'enums',
              label: '枚举值',
              rules: [
                {
                  validator: (_: any, value: any) => {
                    if (value.some((item: any) => item.enumDesc === '' || item.enumKey === '')) {
                      return Promise.reject('枚举值必填');
                    } else {
                      return Promise.resolve();
                    }
                  },
                  trigger: 'blur',
                },
              ],
              render: () => (
                <Table.Edit
                  defaultValue={[{ sortkey: 1, enumKey: '', enumDesc: '' }]}
                  scroll={{ scrollToFirstRowOnChange: true, y: 200 }}
                  pagination={{
                    locale: {
                      page: '页',
                    },
                    showTotal: (total: any) => `共 ${total} 条数据`,
                  }}
                  columns={[
                    {
                      title: '序号',
                      dataIndex: 'sortkey',
                      width: 180,
                      onCell: (record: any) => {
                        return {
                          filed: 'sortkey',
                          record,
                        };
                      },
                    },
                    {
                      title: '参数值',
                      dataIndex: 'enumKey',
                      showSorterTooltip: false,
                      onCell: (record: any) => {
                        return {
                          editable: true,
                          filed: 'enumKey',
                          record,
                          rules: [
                            { required: true, message: '请输入参数值' },
                            {
                              pattern: /^-?[0-9]\d*$/,
                              message: '请输入整数',
                            },
                          ],
                        };
                      },
                    },
                    {
                      title: '参数描述',
                      dataIndex: 'enumDesc',
                      showSorterTooltip: false,
                      onCell: (record: any) => ({
                        editable: true,
                        filed: 'enumDesc',
                        record,
                        rules: [{ required: true, message: '请输入参数描述' }],
                      }),
                    },
                  ]}
                  createRowData={(val: any): object => {
                    return {
                      enumKey: '',
                      enumDesc: '',
                    };
                  }}
                />
              ),
            },
          ],
        ]);
        break;
    }
  }, [selectType]);
  const transFormData = (data: any) => {
    if (_.isEmpty(data)) {
      return data;
    }
    let { attributeValue, ...rest } = data;
    if (attributeValue.booleanEnums) {
      return {
        ...rest,
        booleanEnums: attributeValue.booleanEnums.map((item: any, index: any) => ({
          ...item,
          sortkey: index + 1,
        })),
      };
    }
    if (attributeValue.enums) {
      return {
        ...rest,
        enums: attributeValue.enums.map((item: any, index: any) => ({
          ...item,
          sortkey: index + 1,
        })),
      };
    }
    console.log({ ...rest, ...attributeValue }, '{ ...rest, ...attributeValue }');
    return { ...rest, ...attributeValue };
  };
  return (
    <>
      <Form.Layout
        data={transFormData(data)}
        formItemData={formItemData}
        request={(val: any) => {
          if (data.id) {
            val.id = data.id;
          }
          onFinish(val);
        }}
      ></Form.Layout>
    </>
  );
};

export default App;
